<template>
	<view class="messages">
		<view class="list">
			<view
				class="message"
				v-for="msg in messages"
				:key="msg.id"
			>
				<MsgItem
					:message="msg"
					@click="actionScheme({scheme:msg.scheme})"
				/>
			</view>
			<aha-loadmore :status="loadStatus" />
		</view>
		<AhaTabbar />
	</view>
</template>

<script>
import { refreshMsgList, getMsgList } from '@/api/message'
import { actionScheme, qsScheme } from '@/utils/scheme'
import { adaMessages } from '@/utils/adaptive'
import MsgItem from './components/MsgItem'

export default {
  components: {
    MsgItem
  },
  data() {
    return {
      componentName: 'messages',
      pageNum: 1,
      pageSize: 10,
      loadStatus: 'loading',
      messages: [],
      systemInform: {}
    }
  },
  onShow() {
    this.loadMessages(1)
    /* 获取未读 */
    this.$storeAction('getUnreadCount')
    uni.$on('refreshMessages', this.refreshList)
  },
  onHide() {
    uni.$off('refreshMessages')
  },
  onReachBottom() {
    if (this.loadStatus === 'loadmore') {
      this.loadMessages(this.pageNum + 1)
    }
  },
  onPullDownRefresh() {
    this.loadMessages(1)
  },
  methods: {
    actionScheme,
    /**
     * 加载系统消息
     */
    async getSystemInform() {
      return {
        id: 'systemInfom',
        scheme: 'systemInform',
        avatar: 'https://aha-public-1301319986.cos.ap-shanghai.myqcloud.com/icon/systemInform.png',
        name: '系统通知',
        updateTime: Date.now(),
        content: '查看系统通知',
        unreadCount: 0,
      }
    },
    /**
     * 分页加载消息列表
     */
    async loadMessages(pageNum = this.pageSize) {
      try {
        pageNum === 1 && this.$loading()

        let messages = await this.$pageDataSet({
          request: () => getMsgList({
            pageNum: this.pageNum,
            pageSize: this.pageSize
          }),
          pageNum,
          key: 'messages'
        })

        messages = messages.map(msg => adaMessages(msg, qsScheme({
          scheme: 'chat',
          id: msg.chatterUserInfo.userId
        })))
        if (pageNum === 1) {
          this.messages = [await this.getSystemInform()].concat(messages)
        } else {
          this.messages = messages
        }
        console.log(this.messages)
      } catch (err) {
        this.loadStatus = 'loadmore'
        console.error(err)
      }
      this.$hideLoading()
      uni.stopPullDownRefresh()
    },
    /**
     * 刷新，判断是否有新消息进入
     */
    async refreshList() {
      const res = await refreshMsgList()
      const removeId = {}

      const messages = res.map(msg => {
        console.log(msg)
        const data = adaMessages(msg, `chat^id:${ msg.chatterUserInfo.userId }`)

        removeId[ data.id ] = 1
        return data
      })

      if (messages.length > 0) {
        /* 去掉原来已经存在的对话框 */
        this.messages = this.messages.filter(msg => !removeId[ msg.id ])
        /* 从头部插入新的对话框 */
        this.messages = messages.concat(this.messages)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.messages {
  .message {
    border-bottom: $border1;
  }
}
</style>
